package org.project.product.android.pfe_fanta;

import org.project.product.android.pfe.fanta.R;
import org.project.product.android.pfe.fanta.adapter.DataManagerFacade;
import org.project.product.android.pfe.fanta.domain.Category;
import org.project.product.android.pfe.fanta.util.Utils;

import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class EditOrDeleteCategoryActivity extends ActivityParent {

	private Category categorySelected;

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		this.setContentView(R.layout.option_category);
		categorySelected = (Category) getIntent().getExtras().getSerializable(
		        Utils.CATEGORY_SELECTED);
		((TextView) findViewById(R.id.title)).setText("Category : "
		        + categorySelected.getName());
		listenAction();
	}

	private void listenAction() {

		final EditText labelEdit = (EditText) findViewById(R.id.edit_category_label);
		final EditText descEdit = (EditText) findViewById(R.id.edit_description);

		labelEdit.setText(categorySelected.getName());
		descEdit.setText(categorySelected.getDescription());

		View deleteBt = findViewById(R.id.bt_delete_category);
		deleteBt.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				confirmDelete();
			}
		});

		View editBt = findViewById(R.id.bt_edit_category);
		editBt.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				if (Utils.checkEditText(getApplicationContext(), labelEdit,
				        descEdit)) {
					categorySelected.setName(labelEdit.getText().toString());
					categorySelected.setDescription(descEdit.getText()
					        .toString());
					DataManagerFacade.getInstance(v.getContext())
					        .updateCategory(categorySelected);
					finish();
				}

			}
		});

	}

	private void confirmDelete() {

		Builder dialog = new Builder(this);
		dialog.setTitle("Confirmation");
		dialog.setMessage("Voulez vous supprimer cette categorie et ses produits");
		dialog.setPositiveButton("OK", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				DataManagerFacade
				        .getInstance(EditOrDeleteCategoryActivity.this)
				        .deleteCategory(categorySelected);
				finish();

			}
		});
		dialog.setNegativeButton("Annuler", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();

			}
		});
		dialog.show();
	}

}
